<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import { deleteDistributeTableApi, getDistributeTableListApi } from "@/api/clusters/distributeTables";
import Edit from './component/edit.vue';
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useLogic } from "@/views/system/user/logic/logic";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
const router = useRouter();
defineOptions({
  name: "distributeTablesIndex",
});
const { t } = useI18n();
const pageSizeOps = ref(pageSizeOptions)
const {deptTreeList,getDeptTree}  = useLogic()
onMounted(async () =>{
  await getDeptTree()
})

// 搜索处理
const searchParams = ref({
  page: 1,
  pageSize: 10,
  serverKey: undefined,
  table: undefined,
  flag:undefined,
  timeBy:[],
  deptId: undefined,
});

// 搜索字段配置
const searchFields = ref([
  {
    prop: "serverKey",
    name: t('clusters.distributeTablePage.serverKey'),
    type: "input",
    placeholder: t('clusters.distributeTablePage.serverKeyPlaceholder'),
  },
  {
    prop: "table",
    name: t('clusters.distributeTablePage.tableName'),
    type: "input",
    placeholder: t('clusters.distributeTablePage.tableNamePlaceholder'),
  },
  {
    prop: "flag",
    name: t('clusters.distributeTablePage.flag'),
    type: "input",
    placeholder: t('clusters.distributeTablePage.flagPlaceholder'),
  },
  {
    prop: "timeBy",
    name: t('clusters.distributeTablePage.timeBy'),
    type: "select",
    formOptions: [
      { val: 1, label: t('clusters.distributeTablePage.year') },
      { val: 2, label: t('clusters.distributeTablePage.month') },
      { val: 3, label: t('clusters.distributeTablePage.day') },
    ],
    defaultValue: -1,
  },
  { prop: 'deptId', name: t("products.devicePage.deptId"), type: 'cascader', cascaderOptions: deptTreeList, ops: { valueField: 'id', labelField: 'name', emitPath: false, checkStrictly: true } },
  { prop: 'timeRange', name: t("buttons.timeRange"), type: 'datetimeRange', clearable: true, isHidden: false, },
]);

// 分发表列表数据
const distributeTableList = ref<any[]>([]);
const total = ref(0);

const loading = ref(false);

// 加载分发表列表
const loadDistributeTableList = async () => {
  try {
    loading.value = true;
    const response = await getDistributeTableListApi({
      ...searchParams.value
    });

    if (response.code === 0) {
      if(!response.data.list){
        response.data.list = []
      }
      distributeTableList.value = response.data.list;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.message || t('clusters.distributeTablePage.getListFail'));
    }
    loading.value = false;
  } catch (error) {
    total.value = 0
    loading.value = false;
    ElMessage.error(t('clusters.distributeTablePage.getListFail')+error.message);
    console.error('Failed to load distribute table list:', error);
  }
};

const  handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
}
const handleSearch = (params: any) => {
  searchParams.value.page = 1
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  // 加载数据
  loadDistributeTableList();
};
const handleReset = (e:any) => {
}
// 删除分发表
const handleDelete = async (id: number) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      t('clusters.distributeTablePage.deleteConfirm'),
      t('clusters.distributeTablePage.deleteTitle'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning',
      }
    );

    if (confirmResult === 'confirm') {
      const response = await deleteDistributeTableApi(id);
      if (response.code === 0) {
        ElMessage.success(t('clusters.distributeTablePage.deleteSuccess'));
        await loadDistributeTableList();
      } else {
        ElMessage.error(response.message || t('clusters.distributeTablePage.deleteFail'));
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('clusters.distributeTablePage.deleteFail'));
      console.error('Failed to delete distribute table:', error);
    }
  }
};

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  console.log(pageSize);
  searchParams.value.pageSize = pageSize;
  loadDistributeTableList();
};
const handlePaginationPageChange = (page: number) => {
  console.log(page);
  searchParams.value.page = page;
  loadDistributeTableList();
};

// 初始加载
onMounted(() => {
  loadDistributeTableList();
});

// 格式化时间分片规则
const formatTimeBy = (timeBy: number) => {
  const timeByMap = {
    1: t('clusters.distributeTablePage.year'),
    2: t('clusters.distributeTablePage.month'),
    3: t('clusters.distributeTablePage.day'),
  };
  return timeByMap[timeBy as keyof typeof timeByMap] || t('clusters.distributeTablePage.unknownRule');
};
// 格式化过期状态
const formatExpireStatus = (isExpire: number) => {
  return isExpire === 1 ? t('clusters.distributeTablePage.enabled') : t('clusters.distributeTablePage.disabled');
};

// 格式化过期时间（秒级时间戳转日期时间）
const formatDuration = (timestamp: number) => {
  if (timestamp <= 0) return t('clusters.distributeTablePage.notSet');
  const date = new Date(timestamp * 1000);
  return date.toLocaleString();
};

// 添加编辑对话框状态
const dialogVisible = ref(false);
const selectedTableId = ref(0);

// 编辑分发表
const handleEdit = (id: number) => {
  selectedTableId.value = id;
  dialogVisible.value = true;
};

const handleView = (row:any) => {
  router.push({
    path: '/dataCenter/iotdata',
    query: {
      distributeTableId: row.id,
      deptId: row.deptId
    }
  });
};

</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields="searchFields"
          :initialValues="searchParams"
          :maxVisibleFields="3"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <!-- 表格列表 -->
    <div class="distribute-table-list-container">
      <el-table :data="distributeTableList" border stripe v-loading="loading">
        <el-table-column prop="serverKey" :label="t('clusters.distributeTablePage.serverKey')" min-width="100" />
        <el-table-column prop="table" :label="t('clusters.distributeTablePage.tableName')" min-width="120" />
        <el-table-column prop="flag" :label="t('clusters.distributeTablePage.flag')" min-width="120" />
        <el-table-column prop="timeBy" :label="t('clusters.distributeTablePage.timeBy')" min-width="120">
          <template #default="{ row }">{{ formatTimeBy(row.timeBy) }}</template>
        </el-table-column>
        <el-table-column prop="isExpire" :label="t('clusters.distributeTablePage.expireSetting')" min-width="120">
          <template #default="{ row }">
            <span :class="row.isExpire === 1 ? 'status-expire-enabled' : 'status-expire-disabled'">
              {{ formatExpireStatus(row.isExpire) }}
            </span>
            <template v-if="row.isExpire === 1">({{ formatDuration(row.expireTime) }})</template>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" :label="t('clusters.distributeTablePage.totalAmount')" min-width="100">
          <template #default="{ row }">
            {{row.totalAmount.toLocaleString()}}
          </template>
        </el-table-column>

        <el-table-column prop="totalSize" :label="t('clusters.distributeTablePage.totalSize')" min-width="120">
          <template #default="{ row }">
            {{ row.totalSize.toLocaleString()}}
          </template>
        </el-table-column>
        <el-table-column prop="deptName" :label="t('clusters.deptServerPage.deptName')" width="180" />
        <el-table-column prop="createdAt" :label="t('buttons.createdAt')" min-width="160" />
        <el-table-column :label="t('buttons.action')" min-width="200" fixed="right">
          <template #default="{ row }">
              <div style="display: flex;flex-wrap: wrap;flex-direction: row;justify-content: flex-start;justify-items: flex-start">
                <el-button type="primary" size="small" @click="handleEdit(row.id)">{{ t('buttons.edit') }}</el-button>
                <el-button type="info" size="small" @click="handleView(row)">{{ t('buttons.view') }}</el-button>
                <el-button type="danger" size="small" plain @click="handleDelete(row.id)">{{ t('buttons.delete') }}</el-button>
              </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="pageSizeOps"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePaginationSizeChange"
          @current-change="handlePaginationPageChange"
        />
      </div>
    </div>

    <!-- 编辑对话框 -->
    <Edit
      v-model:visible="dialogVisible"
      :table-id="selectedTableId"
      @success="loadDistributeTableList"
    />
  </el-card>
</template>

<style scoped lang="scss">
.distribute-table-list-container {
  padding: 20px 0;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 状态样式保留
.status-active {
  color: #67c23a;
}

.status-deleted {
  color: #909399;
}

.status-expire-enabled {
  color: #e6a23c;
}

.status-expire-disabled {
  color: #909399;
}
</style>
